package hluck.me.srorage.sys.controller;

import hluck.me.srorage.sys.common.ActiveUser;
import hluck.me.srorage.sys.common.ResultObj;
import hluck.me.srorage.sys.common.WebUtils;
import hluck.me.srorage.sys.domain.SysLogLogin;
import hluck.me.srorage.sys.service.SysLogLoginService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

@RestController
@RequestMapping("login")
public class LoginController {

    @Autowired
    private SysLogLoginService logLoginService;

    @RequestMapping("login")
    public ResultObj login(String loginname, String pwd){
        Subject subject = SecurityUtils.getSubject();
        UsernamePasswordToken token = new UsernamePasswordToken(loginname, pwd);
        try {
            subject.login(token);
            ActiveUser user= (ActiveUser) subject.getPrincipal();
            WebUtils.getSession().setAttribute("user",user.getUser());

            //记录登录日志
            SysLogLogin sysLogLogin=new SysLogLogin();
            sysLogLogin.setLoginname(user.getUser().getName()+"-"+user.getUser().getLoginname());
            sysLogLogin.setLoginip(WebUtils.getRequest().getRemoteAddr());
            sysLogLogin.setLogintime(new Date());
            logLoginService.save(sysLogLogin);
            return ResultObj.LOGIN_SUCCESS;
        }catch (AuthenticationException e){
            e.printStackTrace();
            return ResultObj.LOGIN_ERROR_PASS;
        }
    }
}
